package com.fuego.creditsystemcommodity.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fuego.creditsystemcommodity.mapper.HouseMapper;
import com.fuego.creditsystemcommodity.service.IHouseInfoService;
import com.fuego.creditsystemcommodity.service.IHouseService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.example.dto.Result;
import org.example.entity.Good;
import org.example.entity.House;
import org.example.entity.HouseInfo;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.example.utils.RedisConstants.HOUSE_INFO_STOCK_KEY;


@Service
public class HouseServiceImpl extends ServiceImpl<HouseMapper, House> implements IHouseService {


    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IHouseInfoService houseInfoService;

    @Override
    public Result queryHouseOfOwner(Long ownerId) {
        // 查询优惠券信息
        List<House> houses = getBaseMapper().queryHouseOfOwner(ownerId);
        // 返回结果
        return Result.ok(houses);
    }

    @Override
    @Transactional
    public void addHouseInfo(House house) {
        // 保存优惠券
        save(house);
        // 保存秒杀信息
        HouseInfo houseInfo = new HouseInfo();
        houseInfo.setHouseId(house.getId());
        houseInfo.setStock(house.getStock());

        houseInfoService.save(houseInfo);
        //保存秒杀库存到redis中
        stringRedisTemplate.opsForValue().set(HOUSE_INFO_STOCK_KEY+house.getId(),house.getStock().toString());
    }

    @Override
    public Result queryAllHouse() {
        List<House> houses = getBaseMapper().queryAllHouse();
        // 返回结果
        return Result.ok(houses);
    }

    @Override
    public Result queryHouseById(Long houseId) {
        List<House> houses = getBaseMapper().queryHouseById(houseId);


        // 返回结果
        return Result.ok(houses);
    }


    public Result pageHouse(Integer page, Integer pageSize) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            PageHelper.startPage(page, pageSize);
            List<House> houses = getBaseMapper().queryAllHouse();
            PageInfo<House> pageInfo = new PageInfo<>(houses);

            resultMap.put("houses", pageInfo.getList());
            resultMap.put("total", pageInfo.getTotal());
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            PageHelper.clearPage();
        }
        return Result.ok(resultMap);
    }

    public Result searchHouse(String houseName) {
        List<House> houses = getBaseMapper().searchHouse(houseName);

        return Result.ok(houses);
    }

}
